﻿using Windows.Globalization.NumberFormatting;
using CommunityToolkit.WinUI.Controls;
using DimensionsHelper.Client.WinUi.Extensions;

namespace DimensionsHelper.Client.WinUi.Views;

public sealed partial class SettingsPage : Page
{
    private static readonly SolidColorBrush TransparentBrush = new(Colors.Transparent);

    private int _lastNavigationMode;

    public SettingsPage()
    {
        ViewModel = App.GetService<SettingsViewModel>();
        InitializeComponent();
        Loaded += SettingsPage_Loaded;

        HistoryKeptNumberBox.NumberFormatter = new DecimalFormatter
        {
            IntegerDigits = 1,
            FractionDigits = 0,
            IsDecimalPointAlwaysDisplayed = false,
            NumberRounder = new IncrementNumberRounder
            {
                Increment = 1,
                RoundingAlgorithm = RoundingAlgorithm.RoundHalfUp
            }
        };

        HistorySettingsExpander.Items.Add(
            CreateHistorySettingsCard("清空所有", (_, _) => App.ClearAllHistory()));
        AddRegisteredViewModelClearCard();
    }


    public SettingsViewModel ViewModel
    {
        get;
    }


    private void SettingsPage_Loaded(object sender, RoutedEventArgs e)
    {
        if (App.MainWindow.Content is FrameworkElement rootElement)
        {
            ThemeModeComboBox.SelectedIndex = rootElement.RequestedTheme switch
            {
                ElementTheme.Default => 2,
                ElementTheme.Light => 0,
                ElementTheme.Dark => 1,
                _ => ThemeModeComboBox.SelectedIndex
            };
        }

        if (App.IsCurrentNavigationLeftMode())
        {
            NavigationLocationComboBox.SelectedIndex = 0;
            _lastNavigationMode = 0;
        }
        else
        {
            NavigationLocationComboBox.SelectedIndex = 1;
            _lastNavigationMode = 1;
        }
    }


    private void ThemeModeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        string? selectedTheme = ((ComboBoxItem)ThemeModeComboBox.SelectedItem)?.Tag?.ToString();
        if (selectedTheme == null)
        {
            return;
        }

        if (App.MainWindow.Content is FrameworkElement rootElement)
        {
            ElementTheme theme = App.GetEnum<ElementTheme>(selectedTheme);
            rootElement.RequestedTheme = theme;
            switch (theme)
            {
                case ElementTheme.Light:
                {
                    App.SetCaptionButtonColor(Colors.Black);
                    break;
                }

                case ElementTheme.Dark:
                {
                    App.SetCaptionButtonColor(Colors.White);
                    break;
                }

                case ElementTheme.Default:
                {
                    App.ApplySystemThemeToCaptionButtons();
                    break;
                }
            }
        }

        UIHelper.AnnounceActionForAccessibility(ThemeModeComboBox, $"主题颜色切换到{selectedTheme}",
            "ThemeChangedNotificationActivityId");
    }

    private void NavigationLocation_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (NavigationLocationComboBox.SelectedIndex == _lastNavigationMode)
        {
            return;
        }

        if (App.MainWindow.Content is not ShellPage)
        {
            return;
        }

        App.SetCurrentNavigationMode(NavigationLocationComboBox.SelectedIndex == 0);
        _lastNavigationMode = NavigationLocationComboBox.SelectedIndex;
    }

    private static SettingsCard CreateHistorySettingsCard(string header, RoutedEventHandler clearButtonClick)
    {
        SettingsCard card = new()
        {
            Header = header
        };

        Button innerButton = new()
        {
            Background = TransparentBrush,
            BorderBrush = TransparentBrush,
            Content = new FontIcon
            {
                FontFamily = FontHelper.FluentUiSystemFont,
                FontSize = 24,
                Width = 24,
                Height = 24,
                Glyph = char.ConvertFromUtf32((int)FluentSystemIconSymbols.ic_fluent_dismiss_24_regular)
            }
        };

        ToolTipService.SetToolTip(innerButton, "清空");

        innerButton.Click += clearButtonClick;
        card.Content = innerButton;

        return card;
    }


    private void AddRegisteredViewModelClearCard()
    {
        foreach (RecordHistoryViewModel viewModel in App.GetRecordHistoryViewModels())
        {
            HistorySettingsExpander.Items.Add(CreateHistorySettingsCard(
                viewModel.Section,
                async void (_, _) => await viewModel.ClearHistoricalListAsync()));
        }
    }
}